using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using Prism.Commands;
using Prism.Mvvm;

namespace CPlatePrintSys.Win.ViewModels
{
    public class OutputDirectoryConfigViewModel : BindableBase
    {
        private readonly IGlobalConfigService _configService;

        // 输出目录配置
        private OutputDirectoryConfig _outputDirectoryConfig;
        public OutputDirectoryConfig OutputDirectoryConfig
        {
            get { return _outputDirectoryConfig; }
            set { SetProperty(ref _outputDirectoryConfig, value); }
        }

        // 验证消息
        private string _validationMessage;
        public string ValidationMessage
        {
            get { return _validationMessage; }
            set { SetProperty(ref _validationMessage, value); }
        }

        // 命令
        public ICommand BrowseOutputPathCommand { get; }

        public OutputDirectoryConfigViewModel(IGlobalConfigService configService)
        {
            _configService = configService;

            BrowseOutputPathCommand = new DelegateCommand(BrowseOutputPath);

            // 初始化配置对象
            OutputDirectoryConfig = new OutputDirectoryConfig
            {
                OutputPath = @"\\192.168.1.2\share\C-plate\",
                EnableBackup = true,
                BackupRetentionDays = 30
            };

            LoadConfig();
        }

        private async void LoadConfig()
        {
            try
            {
                OutputDirectoryConfig = await _configService.GetOutputDirectoryConfigAsync();
            }
            catch (Exception ex)
            {
                // 如果加载失败，使用默认配置
                OutputDirectoryConfig = new OutputDirectoryConfig
                {
                    OutputPath = @"\\192.168.1.2\share\C-plate\",
                    EnableBackup = true,
                    BackupRetentionDays = 30
                };
            }
        }

        public async Task SaveOutputDirectory()
        {
            try
            {
                await _configService.UpdateOutputDirectoryConfigAsync(OutputDirectoryConfig, "System");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"保存输出目录配置失败: {ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        // 添加更新输出路径的方法，确保触发UI更新
        public void UpdateOutputPath(string newPath)
        {
            OutputDirectoryConfig.OutputPath = newPath;
            RaisePropertyChanged(nameof(OutputDirectoryConfig));
        }

        // 验证路径并保存
        public async Task ValidateAndSavePath(string path)
        {
            ValidationMessage = ""; // 清除之前的验证消息

            if (string.IsNullOrWhiteSpace(path))
            {
                ValidationMessage = "路径不能为空";
                return;
            }

            try
            {
                // 检查路径格式
                if (!IsValidPathFormat(path))
                {
                    ValidationMessage = "路径格式不正确，请检查路径格式";
                    return;
                }

                // 检查路径是否存在（对于网络路径，只检查格式）
                if (path.StartsWith(@"\\"))
                {
                    // 网络路径，只验证格式
                    if (!IsValidNetworkPath(path))
                    {
                        ValidationMessage = "网络路径格式不正确，请使用 \\\\服务器名\\共享名\\路径 格式";
                        return;
                    }
                }
                else
                {
                    // 本地路径，检查是否存在
                    if (!Directory.Exists(path))
                    {
                        ValidationMessage = "目录不存在，请检查路径是否正确";
                        return;
                    }
                }

                // 路径验证通过，保存配置（不显示成功消息）
                UpdateOutputPath(path);
                await SaveOutputDirectory();
                // 不设置成功消息，保持 ValidationMessage 为空
            }
            catch (Exception ex)
            {
                ValidationMessage = $"路径验证失败: {ex.Message}";
            }
        }

        // 验证路径格式
        private bool IsValidPathFormat(string path)
        {
            try
            {
                // 检查是否包含非法字符
                var invalidChars = Path.GetInvalidPathChars();
                if (path.IndexOfAny(invalidChars) >= 0)
                {
                    return false;
                }

                // 检查路径长度
                if (path.Length > 260)
                {
                    return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        // 验证网络路径格式
        private bool IsValidNetworkPath(string path)
        {
            try
            {
                // 网络路径应该以 \\ 开头
                if (!path.StartsWith(@"\\"))
                {
                    return false;
                }

                // 检查是否包含服务器名和共享名
                var parts = path.Substring(2).Split('\\');
                if (parts.Length < 2)
                {
                    return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        private async void BrowseOutputPath()
        {
            try
            {
                var dialog = new System.Windows.Forms.FolderBrowserDialog();
                dialog.Description = "选择输出目录";
                dialog.ShowNewFolderButton = true;

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // 使用新的更新方法
                    UpdateOutputPath(dialog.SelectedPath);
                    
                    // 强制刷新UI
                    var view = System.Windows.Application.Current.MainWindow?.FindName("OutputDirectoryConfigView") as Views.OutputDirectoryConfigView;
                    view?.RefreshUI();
                    
                    // 立即保存配置
                    await SaveOutputDirectory();
                    
                    // 清除验证消息（不显示成功消息）
                    ValidationMessage = "";
                }
            }
            catch (Exception ex)
            {
                ValidationMessage = $"选择目录失败: {ex.Message}";
            }
        }
    }
} 